package net.awpspace.walkman.view;

import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.game.GameCanvas;
import javax.microedition.lcdui.game.Sprite;

import net.awpspace.walkman.piano.PianoCanvas;
import net.awpspace.walkman.utils.BackStack;
import net.awpspace.walkman.utils.ImageUtils;

/**
 * Screen: Main menu
 * 
 * @author Diep AwpSpace
 * 
 */
public class Menu extends GameCanvas {

	private Sprite sLibrary;
	private Sprite sNowPlaying;
	private Sprite sPiano;

	private Sprite sSelected;

	public Menu(boolean arg0) {
		super(true);
		this.setFullScreenMode(true);

		sLibrary = new Sprite(ImageUtils.getImage(ImageUtils.SHEET_LIBRARY),
				221, 120);
		sLibrary.setPosition(10, 10);
		sNowPlaying = new Sprite(
				ImageUtils.getImage(ImageUtils.SHEET_NOWPLAYING), 221, 120);
		sNowPlaying.setPosition(10, 140);
		sPiano = new Sprite(ImageUtils.getImage(ImageUtils.SHEET_PIANO), 221,
				120);
		sPiano.setPosition(10, 270);
	}

	/**
	 * custom drawing
	 */
	public void paint(Graphics g) {
		g.setColor(0x000000);
		g.fillRect(0, 0, 240, 400);
		sLibrary.paint(g);
		sNowPlaying.paint(g);
		sPiano.paint(g);

		flushGraphics();
	}

	/**
	 * onClick method handler
	 */
	protected void pointerPressed(int x, int y) {
		sSelected = getSelectedSprite(x, y);
		if (sSelected != null) {
			sSelected.setFrame(1);
		}
		repaint();
	}

	/**
	 * UI changing handler
	 */
	protected void pointerReleased(int x, int y) {
		if (sSelected != null) {
			sSelected.setFrame(0);
		}
		repaint();
		Sprite tmp = getSelectedSprite(x, y);
		if (tmp != null && tmp.equals(sSelected)) {
			if (sSelected.equals(sLibrary)) {
				BackStack.getInstance(null).store(this);
				new Library().show();
			} else if (sSelected.equals(sNowPlaying)) {
				BackStack.getInstance(null).forward(new Playing(true));
			} else if (sSelected.equals(sPiano)) {
				PianoHolder holder = new PianoHolder();
				PianoCanvas canvas = new PianoCanvas(holder);
				canvas.addInstrumentModel(holder);
				holder.addInstrumentModelListener(canvas);
				holder.startApp();
				BackStack.getInstance(null).forward(canvas);
			}
		}
	}

	/**
	 * Get selected sprite from coordinate
	 * 
	 * @param x
	 * @param y
	 * @return
	 */
	private Sprite getSelectedSprite(int x, int y) {
		if (x > 10 && x < 230) {
			if (y > 10 && y < 130) {
				return sLibrary;
			}
			if (y > 140 && y < 260) {
				return sNowPlaying;
			}
			if (y > 270 && y < 390) {
				return sPiano;
			}
		}
		return null;
	}
}
